/************************************************************************
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)                           *
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。   *
 * 版权所有：忠旺机械设备制造有限公司                                       *
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。   *
 * 软件版本：Ver 1.0.0                                                   *
 * 文件路径：com.zhongwang.mms.module.buy.controller                     *
 * 创建时间：2020年08月07日 18时27分                                       *
 *======================================================================*/
package com.zhongwang.mms.module.buy.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;


import com.zhongwang.mms.base.BaseController;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.VwDictCommon;
import com.zhongwang.mms.module.buy.model.ExportRecPlanModel;
import com.zhongwang.mms.module.buy.model.ReceiveReportPlanModel;
import com.zhongwang.mms.module.buy.model.ReportPlanModel;
import com.zhongwang.mms.module.buy.service.GetReportPlanApiService;
import com.zhongwang.mms.module.purchase.model.PurWarQueryModel;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.FTPUtil;
import com.zhongwang.mms.util.FileUtils;
import com.zhongwang.mms.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/buy/getReportPlanList")
@Log4j2
/**
 *@name: GetReportPlanApiController
 *@description: 对PDM系统接口
 *@author: 徐一贺
 *@coddingDate: 2020/8/7 18:28
 *@version: v1.0
 **/
public class GetReportPlanApiController extends BaseController {

    @Autowired
    private GetReportPlanApiService getReportPlanApiService;
    @Autowired
    public LogService logService;
    @Value("${user.upload.path}")
    private String uploadPath;

    /**
     * @name: page
     * @description: 跳转到提报计划接收页面
     * @param: [model]
     * @returnType: java.lang.String
     * @author: 徐一贺
     * @coddingDate: 2020/8/7 18:41
     * @version: v1.0
     **/
    @GetMapping
    @RequiresPermissions("buy:planreceive:view")
    public String page(Model model) {
        List<VwDictCommon> vwDictCommonList = getReportPlanApiService.findVwDictCommonListByMat();
        model.addAttribute("vwDictCommonList", vwDictCommonList);
        return "buy/getReportPlan/page";
    }

    /**
     * @name: plannerEdit
     * @description: 跳转到计划号与计划员编辑页面
     * @param: [model]
     * @returnType: java.lang.String
     * @author: 徐一贺
     * @coddingDate: 2020/8/8 13:06
     * @version: v1.0
     **/
    @GetMapping("/plannerEdit")
    @RequiresPermissions("buy:plandistribution:view")
    public String plannerEdit(Model model) {
        return "buy/plannerEdit/page";
    }

    /**
     * @name: receiveList
     * @description: 获取未接收列表
     * @param: [queryParam]
     * @returnType: com.zhongwang.mms.common.JsonResult
     * @author: 徐一贺
     * @coddingDate: 2020/8/7 18:42
     * @version: v1.0
     **/
    @ResponseBody
    @PostMapping("/receive/list")
    @RequiresPermissions("buy:planreceive:view")
    public JsonResult receiveList(ReceiveReportPlanModel queryParam) {
        startPage();
        List<ReceiveReportPlanModel> list;
        if(queryParam.getRecMark().intValue() == 0){
            list = getReportPlanApiService.getToBeReceivedList(queryParam);
        }else{
            list = getReportPlanApiService.getReceivedList(queryParam);
        }
        return jsonResult(list);
    }
//    /**
//     * 列表 导出
//     * @param queryParam 查询条件
//     * @return list
//     */
//    @PostMapping("/exportExcel")
//    @ResponseBody
//    @RequiresPermissions({"purwar:purwarquery:export"})
//    public JsonResult exportExcel(ReceiveReportPlanModel queryParam) {
//        return getReportPlanApiService.exportExcelRecPlan(queryParam);
//    }

    /**
     * 导出接收的提报计划
     *
     * @param queryParam 查询条件
     * @param response 下载
     * @throws IOException 异常
     */
    @GetMapping("/exportExcelAllData")
    public void exportExcelAllData(ReceiveReportPlanModel queryParam, HttpServletResponse response) throws IOException {
        // 记录开始时间（纳秒）
        long startTime = System.nanoTime();

        // 1. 设置响应头（文件名、格式）
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        // 文件名编码（避免中文乱码）
        String fileName = URLEncoder.encode("接收的提报计划", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");
        // 2. 构建ExcelWriter（使用响应流）
        ExcelWriter excelWriter = null;
        int exportDataCount = 0;
        try {
            // 初始化Writer：指定响应输出流、数据类型、不自动关闭流（手动控制）
            excelWriter = EasyExcel.write(response.getOutputStream(), ExportRecPlanModel.class)
                    .autoCloseStream(false) // 关键：避免响应流被提前关闭
                    .build();

            // 3. 创建第一个Sheet页（索引0，名称自定义）
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "接收的提报计划")
                    .build();

            // 4. 分页查询并写入数据
            int pageNum = 1;
            while (true) {
                // 4.1 分页查询数据
                List<ExportRecPlanModel> dataList = getReportPlanApiService.queryReceivedSubmissionPlan(pageNum, 5000, queryParam);
                if (dataList.isEmpty()) {
                    break; // 无更多数据，退出循环
                }
                exportDataCount += dataList.size();
                // 4.2 写入当前页数据到Sheet（同一Sheet追加）
                excelWriter.write(dataList, writeSheet);
                // 4.3 刷新流（可选，大文件建议加，避免数据积压）
                response.getOutputStream().flush();
                pageNum++;
            }
        } finally {
            // 5. 关闭资源（必须执行，否则文件损坏）
            if (excelWriter != null) {
                excelWriter.finish(); // 完成写入，释放资源
            }
            // 关闭响应流（建议手动关闭，确保数据刷出）
            response.getOutputStream().close();
            // 记录开始时间（纳秒）
            long endTime = System.nanoTime();
            // 计算耗时（秒）
            double elapsedSeconds = (endTime - startTime) / 1_000_000_000.0;
            logService.saveLog("采购管理-提报计划接收-导出接收的提报计划", "导出接收的"+exportDataCount+"条提报计划，耗时"+elapsedSeconds+"秒。");
        }
    }

    /**
     * @name: receivePlans
     * @description: 批量接收
     * @param: [ids] 接收计划的ID
     * @returnType: com.zhongwang.mms.common.JsonResult
     * @author: 徐一贺
     * @coddingDate: 2020/8/7 19:36
     * @version: v1.0
     **/
    @ResponseBody
    @PostMapping("/receive/plans")
    @RequiresPermissions(value = {"buy:planreceive:edit", "buy:planchangereceive:edit"}, logical = Logical.OR)
    public JsonResult receivePlans(String ids) {
        return getReportPlanApiService.receivePlans(ids);
    }

    /**
     * @name: editList
     * @description: 获取未编辑列表
     * @param: [queryParam]
     * @returnType: com.zhongwang.mms.common.JsonResult
     * @author: 徐一贺
     * @coddingDate: 2020/8/8 13:28
     * @version: v1.0
     **/
    @ResponseBody
    @PostMapping("/edit/list")
    @RequiresPermissions("buy:planreceive:view")
    public JsonResult editList(ReportPlanModel queryParam) {
        startPage();
        List<ReportPlanModel> list = getReportPlanApiService.getEditList(queryParam);
        return jsonResult(list);
    }

    @ResponseBody
    @PostMapping("/edit/isExits")
    /**
     *@name: editIsExits
     *@description: 验证计划员是否存在
     *@param: [planner] 计划员名称
     *@returnType: java.lang.String
     *@author: 徐一贺
     *@coddingDate: 2020/8/8 16:23
     *@version: v1.0
     **/
    public String editIsExits(ReportPlanModel queryParam) {
        Map<String, Boolean> map = new HashMap<String, Boolean>();
        map.put("valid", getReportPlanApiService.plannerIsExits(queryParam.getRppPlanner()));
        String resultString = "";
        ObjectMapper mapper = new ObjectMapper();
        try {
            resultString = mapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return resultString;
    }

    @ResponseBody
    @PostMapping("/edit/save")
    /**
     *@name: editSave
     *@description: 分配计划员和填写计划号
     *@param: [saveParam] 保存参数
     *@returnType: com.zhongwang.mms.common.JsonResult
     *@author: 徐一贺
     *@coddingDate: 2020/8/8 16:41
     *@version: v1.0
     **/
    @RequiresPermissions("buy:plandistribution:edit")
    public JsonResult editSave(ReportPlanModel saveParam) {
        return getReportPlanApiService.savePlanner(saveParam);
    }

    @ResponseBody
    @PostMapping("/edit/submit")
    /**
     *@name: editSubmit
     *@description: 批量提交
     *@param: [saveParam] 保存参数
     *@returnType: com.zhongwang.mms.common.JsonResult
     *@author: 徐一贺
     *@coddingDate: 2020/8/10 08:57
     *@version: v1.0
     **/
    @RequiresPermissions("buy:plandistribution:edit")
    public JsonResult editSubmit(ReportPlanModel submitParam) {
        return getReportPlanApiService.editSubmit(submitParam);
    }

    /**
     * 列表 导出
     *
     * @param exportParam 导出条件
     * @return excel
     */
    @GetMapping("/edit/export")
    @ResponseBody
    @RequiresPermissions("buy:plandistribution:export")
    public void exportExcel(HttpServletResponse response, ReportPlanModel exportParam) {
        getReportPlanApiService.exportExcel(response, exportParam);
    }

    /**
     * @name: importExcel
     * @description: 导入Excel
     * @param: [file]
     * @returnType: void
     * @author: 徐一贺
     * @coddingDate: 2020/8/10 15:28
     * @version: v1.0
     **/
    @PostMapping("/edit/import")
    @ResponseBody
    @RequiresPermissions("buy:plandistribution:add")
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) {
        return success(getReportPlanApiService.importExcel(file));
    }

    /**
     * @name: exportErrorLog
     * @description: 导出错误日志Excel
     * @param: [file]
     * @returnType: void
     * @author: 徐一贺
     * @coddingDate: 2020/8/10 15:28
     * @version: v1.0
     **/
    @GetMapping("/edit/exportErrorLog")
    @ResponseBody
    @RequiresPermissions("buy:plandistribution:export")
    public void exportErrorLog(HttpServletResponse response) {
        getReportPlanApiService.exportErrorLog(response);
    }


    @ResponseBody
    @GetMapping("/download/{id}/{recMark}")
    /**
     *@name: editList
     *@description: 下载文件
     *@param: [queryParam]
     *@returnType: com.zhongwang.mms.common.JsonResult
     *@author: 徐一贺
     *@coddingDate: 2020/8/8 13:28
     *@version: v1.0
     **/
    public void returnUrl(@PathVariable("id") Integer id, @PathVariable("recMark") Integer recMark, HttpServletResponse httpServletResponse) {
        try {
            String filename = getReportPlanApiService.getFilePathById(id, recMark);
            filename = filename.replace("/files/", "/");
            FTPUtil ftpUtil = new FTPUtil();
            String localPath = uploadPath + filename.substring(filename.lastIndexOf("/"));
            File file = new File(localPath);
            file.deleteOnExit();
            ftpUtil.downloadFiles(filename, localPath);
            FileUtils.downloadFile(localPath, httpServletResponse);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    @ResponseBody
    @GetMapping("/downloadById/{id}")
    /**
     *@name: editList
     *@description: 下载文件
     *@param: [queryParam]
     *@returnType: com.zhongwang.mms.common.JsonResult
     *@author: 徐一贺
     *@coddingDate: 2020/8/8 13:28
     *@version: v1.0
     **/
    @RequiresPermissions(value = "buy:planreceive:download,buy:planchangereceive:download,buy:plancheck:edit", logical = Logical.OR)
    public void downloadByUrl(@PathVariable("id") Integer id, HttpServletResponse httpServletResponse) {
        String filename = getReportPlanApiService.getReportPlanByPrimaryKey(id).getRppExtendUrl();
        filename = filename.replace("/files/", "/");
        FTPUtil ftpUtil = new FTPUtil();
        String localPath = uploadPath + filename.substring(filename.lastIndexOf("/"));
        File file = new File(localPath);
        file.deleteOnExit();
        ftpUtil.downloadFiles(filename, localPath);
        FileUtils.downloadFile(localPath, httpServletResponse);
    }

    @ResponseBody
    @PostMapping("/lookFile")
    /**
     *@name: editList
     *@description: 查看文件
     *@param: [queryParam]
     *@returnType: com.zhongwang.mms.common.JsonResult
     *@author: 徐一贺
     *@coddingDate: 2020/8/8 13:28
     *@version: v1.0
     **/
    public JsonResult lookFile(@RequestParam("id") Integer id, @RequestParam("recMark") Integer recMark, HttpServletResponse httpServletResponse) {

        try {
            String filename = getReportPlanApiService.getFilePathById(id, recMark);
            filename = filename.replace("/files/", "/");
            FTPUtil ftpUtil = new FTPUtil();
            String localPath = uploadPath + ShiroUtils.getUserId() + filename.substring(filename.lastIndexOf("/"));
            File file = new File(localPath);
            file.deleteOnExit();
            new File(uploadPath + ShiroUtils.getUserId()).mkdirs();
            ftpUtil.downloadFiles(filename, localPath);
            String lookFileName = new File(localPath).getName();
            return JsonResult.success("", "/files/" + ShiroUtils.getUserId() + "/" + lookFileName);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResult.fail();
        }
    }

    @ResponseBody
    @PostMapping("/lookFileByChange")
    /**
     *@name: editList
     *@description: 下载文件
     *@param: [queryParam]
     *@returnType: com.zhongwang.mms.common.JsonResult
     *@author: 徐一贺
     *@coddingDate: 2020/8/8 13:28
     *@version: v1.0
     **/
    @RequiresPermissions("buy:planchangereceive:edit")
    public JsonResult lookFileByChange(@RequestParam("id") Integer id, @RequestParam("dataType") String dataType, HttpServletResponse httpServletResponse) {
        try {
            String filename = getReportPlanApiService.getFilePathByIdToChange(id, dataType);
            filename = filename.replace("/files/", "/");
            FTPUtil ftpUtil = new FTPUtil();
            String localPath = uploadPath + ShiroUtils.getUserId() + filename.substring(filename.lastIndexOf("/"));
            File file = new File(localPath);
            file.deleteOnExit();
            ftpUtil.downloadFiles(filename, localPath);
            String lookFileName = new File(localPath).getName();
            return JsonResult.success("", "/files/" + ShiroUtils.getUserId() + "/" + lookFileName);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResult.fail();
        }
    }

    /**
     * @name: delAllFile
     * @description: 删除所有文件以及文件夹
     * @param: [path]
     * @returnType: boolean
     * @author: 徐一贺
     * @coddingDate: 2020/8/15 15:03
     * @version: v1.0
     **/
    private boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /**
     * @title: delFolder
     * @description: 删除文件夹
     * @param: [folderPath]
     * @return: void
     * @author: 徐一贺
     * @date: 2020/11/5 17:58
     * @versron: ver 1.0
     */
    private void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

//    /**
//     * @name: returnPlan
//     * @description: 撤销已接收未提交的提报计划
//     * @param: [id]
//     * @returnType: com.zhongwang.mms.common.JsonResult
//     * @author: 徐一贺
//     * @coddingDate: 2020年11月5日17:58:44
//     * @version: v1.0
//     **/
//    @ResponseBody
//    @PostMapping("/return/plan")
//    @RequiresPermissions("buy:planreceive:return")
//    public JsonResult returnPlan(Integer id) {
//        return getReportPlanApiService.returnPlan(id);
//    }
}
